import fetch from "../request";
import api from "../../api";

let dbname = 'zlgchat';
let tablename = 'chatmsg'; // 聊天记录
const msguserTablename = 'msguser'; // 聊天对象信息
let sqlite = {
	//创建数据库或者有该数据库就打开
	openSqlite: function() {
		//创建数据库或者打开
		//这plus.sqlite只在手机上运行
		return new Promise((resolve, reject) => {
			plus.sqlite.openDatabase({
				name: dbname, //数据库名称
				path: "_doc/" + dbname + ".db",
				success(e) {
					resolve(e); //成功回调
				},
				fail(e) {
					reject(e); //失败回调
				},
			});
		});
	},

	// 创建表
	createTable: function() {
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				name: dbname,
				sql: `CREATE TABLE if not exists ${tablename} (
            "id" integer NOT NULL,
            "fromId" integer,
            "toId" integer,
            "msgType" integer,
            "createTime" integer,
            "msg" text,
            "sign" integer,
            PRIMARY KEY ("id")
            );
            `,
				success(e) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: `
            CREATE TABLE if not exists ${msguserTablename} (
            "userId" integer NOT NULL,
            "userName" text,
            "alias" text,
            "avatar" text,
            "createTime" integer,
            PRIMARY KEY ("userId")
            );
            `,
						success(e) {
							resolve(e);
						},
						fail(e) {
							reject(e);
						},
					});
					// resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},



	// 删除表
	dropTable: function() {
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				name: dbname,
				sql: `DROP TABLE ${dbname}.${tablename};`,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},

	// 插入数据
	insertMsg: function(obj, sign = 0) {
		return new Promise((resolve, reject) => {
			if (obj) {
				plus.sqlite.executeSql({
					name: dbname,
					sql: `insert into ${tablename}(fromId, toId, msgType, createTime, msg, sign) VALUES (${obj.fromId || null}, ${obj.toId || null}, ${obj.msgType || null}, ${Date.now()}, '${obj.msg || ''}', ${sign});`,
					success(e) {
						resolve(e);
					},
					fail(e) {
						reject(e);
					},
				});
			} else {
				reject("添加错误");
			}
		});
	},
	/*查询*/
	selectMsg: function(msgbody) {
		var sql = `select * from ${tablename} where 1=1 `;
		if (msgbody && msgbody.fromId && msgbody.toId) {
			sql +=
				` and ((fromId=${msgbody.fromId} and toId=${msgbody.toId}) or (fromId=${msgbody.toId} and toId=${msgbody.fromId}))`;
		} else if (msgbody && msgbody.fromId) {
			sql += ` and fromId=${msgbody.fromId}`;
		} else if (msgbody && msgbody.toId) {
			sql += ` and toId=${msgbody.toId}`;
		}
		if (msgbody && msgbody.msgType) {
			sql += ` and msgType=${msgbody.msgType}`;
		}
		if (msgbody && msgbody.sign) {
			sql += ` and sign=${msgbody.sign}`;
		}
		if (msgbody && msgbody.createTime) {
			sql += ` and createTime<${msgbody.createTime}`;
		}
		sql += ` order by createTime desc`;
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: dbname,
				sql: sql,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},

	// 查询最新一条数据
	selectLastMsg: function(msgbody) {
		var sql = `select * from ${tablename} where msgType!=6 `;
		if (msgbody && msgbody.fromId && msgbody.toId) {
			sql +=
				` and ((fromId=${msgbody.fromId} and toId=${msgbody.toId}) or (fromId=${msgbody.toId} and toId=${msgbody.fromId}))`;
		} else if (msgbody && msgbody.fromId) {
			sql += ` and fromId=${msgbody.fromId}`;
		} else if (msgbody && msgbody.toId) {
			sql += ` and toId=${msgbody.toId}`;
		}
		if (msgbody && msgbody.msgType) {
			sql += ` and msgType=${msgbody.msgType}`;
		}
		sql += ` order by createTime desc limit 1`;
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: dbname,
				sql: sql,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},

	/**
	 * 分页查询
	 * @param page 页码从1开始
	 * @param id    标识id 从这个id往上开始拿数据 为空则不限制
	 * @param msgbody 查询条件体
	 * @returns {Promise<unknown>}
	 */
	pageList: function(msgbody, page = 1, pagesize = 20) {
		// let pagesize = 20;  // 一页20条
		let offset = (page - 1) * pagesize
		let sqlstr = `select * from ${tablename} where 1=1 `
		if (msgbody && msgbody.id) {
			sqlstr += ` and id<${msgbody.id}`
		}
		if (msgbody && msgbody.fromId && msgbody.toId) {
			sqlstr +=
				` and ((fromId=${msgbody.fromId} and toId=${msgbody.toId}) or (fromId=${msgbody.toId} and toId=${msgbody.fromId}))`;
		} else if (msgbody && msgbody.fromId) {
			sqlstr += ` and fromId=${msgbody.fromId}`;
		} else if (msgbody && msgbody.toId) {
			sqlstr += ` and toId=${msgbody.toId}`;
		}
		if (msgbody && msgbody.msgType) {
			sqlstr += ` and msgType=${msgbody.msgType}`;
		} else {
			sqlstr += ` and (msgType=1 or msgType=4)`;
		}
		if (msgbody && msgbody.sign) {
			sqlstr += ` and sign=${msgbody.sign}`;
		}
		if (msgbody && msgbody.createTime) {
			sqlstr += ` and createTime<${msgbody.createTime}`;
		}
		sqlstr += `  order by createTime desc limit ${pagesize} offset ${offset}`
		console.log('查询sql: ', sqlstr)
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: dbname,
				sql: sqlstr,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},

	//关闭数据库
	closeSQL: function() {
		return new Promise((resolve, reject) => {
			plus.sqlite.closeDatabase({
				name: dbname,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},

	//监听数据库是否开启
	isOpen: function(name, path) {
		var ss = name || dbname;
		var qq = path || "_doc/" + dbname + ".db";
		//数据库打开了就返回true,否则返回false
		var open = plus.sqlite.isOpenDatabase({
			name: ss,
			path: qq,
		});
		return open;
	},
	// 插入聊天对象数据
	insertMuser: function(obj) {
		return new Promise((resolve, reject) => {
			if (obj) {
				this.selectMuser({
					userId: obj.userId
				}).then(async res => {
					if (res && res.length === 0) {
						let otherSideUser = await fetch(api.get_user_by_id, {
							userId: obj.userId
						}, 'POST')
						console.log('获取对象用户信息--- ', otherSideUser)
						obj.avatar = otherSideUser.data.user.avatar
						obj.userId = otherSideUser.data.user.userId
						obj.userName = otherSideUser.data.user.userName
						plus.sqlite.executeSql({
							name: dbname,
							sql: `insert into ${msguserTablename}(userId, userName, alias, avatar, createTime) 
                VALUES (${obj.userId || null}, '${obj.userName || ''}', '', '${obj.avatar || ''}', ${Date.now()});`,
							success(e) {
								resolve(e);
							},
							fail(e) {
								reject(e);
							},
						});
					} else {
						resolve();
					}
				}).catch(e => {
					reject(e);
				})
			} else {
				reject("添加错误");
			}
		});
	},
	/*查询*/
	selectMuser: function(query) {
		var sql = `select * from ${msguserTablename} where 1=1 `;
		if (query && query.userId) {
			sql += ` and userId=${query.userId}`;
		}
		sql += ` order by createTime desc`;
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: dbname,
				sql: sql,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	},

	deleteMsg: function(id) {
		var deleteDataByIdSql = `DELETE FROM ${msguserTablename} where 1=1 and userId = '${id}'`;
		plus.sqlite.executeSql({
			name: dbname,
			sql: deleteDataByIdSql,
			success: (res) => {
				console.log(res);
			},
			fail: (e) => {
				console.log(e);
			}
		})

	
	},





	//删除数据库里的数据 TODO: 没做好
	// deleteMsg: function (name, sol, qq, ww, ee) {
	//   if (name !== undefined && sol !== undefined) {
	//     var sql = "delete from " + name + " where " + sol + '="' + qq + '"';
	//     return new Promise((resolve, reject) => {
	//       plus.sqlite.executeSql({
	//         name: dbname,
	//         sql: sql,
	//         success(e) {
	//           resolve(e);
	//         },
	//         fail(e) {
	//           reject(e);
	//         },
	//       });
	//     });
	//   } else {
	//     return new Promise((resolve, reject) => {
	//       reject("错误删除");
	//     });
	//   }
	// },
	//
	// 修改数据
	readMsg: function(query) {
		var sql = `update ${tablename} set sign=1 where 1=1`;
		if (query && query.fromId) {
			sql += ` and fromId=${query.fromId}`;
		}
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				name: dbname,
				sql: sql,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				},
			});
		});
	}
};

//把这些方法导出去
export default sqlite;
